* Randomly reshulffe macro variables :
* -----------------------------------

clear 
set obs 41
gen country_id = _n
* create a random integer between 1 and 41
gen country_rand_id = runiformint(1,41)

*expand to firms - add weights (the original one's; we reshuffle countries, not firm weights in this exercise)
mmerge country_id using ${monte_data_dir}/bvd_country_firmweights_country_`rname'.dta, unmatched(none)
drop _m

* expand years
expand 17
bys BvD country_id: gen year=1994+_n

* merge with country variables (reshuffled); go to firm-year-country level
mmerge country_rand_id year using ${monte_data_dir}/ctry_year_macrodata_`rname'.dta, unmatched(master)


drop _m country_id country_rand_id

*make country weighted average firm-level, collapse to firm-year
foreach var in lngdpgap_ gdppcMP_ hswMP_ lswMP_ vaempMP_ {
	gen firm`var'=`var'*share2_all_1995_
	gen firm`var'foreign=`var'*share2_all_1995_*(1-dom)
	gen firm`var'foreign_weight=share2_all_1995_*(1-dom)
}
collapse (sum) firm* , by(BvDIDnumber year)
sort BvDIDnumber year

* prepare foreign variables
foreach var in gdppcMP_ hswMP_ lswMP_ vaempMP_ {
	by BvDIDnumber: gen dom_share4=firm`var'foreign[1]/firm`var'[1] 
	replace firm`var'foreign=firm`var'foreign/firm`var'foreign_weight
	gen firm`var'share4=dom_share4*log(firm`var'foreign)
	drop dom_share4
}

rename firmlngdpgap_foreign GDPGAP_foreign
rename firmhswMP_share4 HSW_foreign
rename firmlswMP_share4 LSW_foreign	
rename firmgdppcMP_share4 GDPPC_foreign
rename firmvaempMP_share4 VAEMP_foreign

* prepare domestic variables (& log them (besides the lngdpgap))
rename firmlswMP_ LSW
rename firmhswMP_ HSW
rename firmvaempMP_ VAEMP
rename firmgdppcMP_ GDPPC
rename firmlngdpgap_ GDPGAP
foreach var in LSW HSW VAEMP GDPPC {
	replace `var'=log(`var')
}

* match to the rest of the variables, i.e., depvar, stocks, spillover variables. 
mmerge BvD year using ${monte_data_dir}/bvd_year_firmdata_country_`rname'.dta, unmatched(none)
drop _m

*create panel for regressions
xtset lse_id year
sort lse_id year